Skip to main content

Lab 01: Create VPC and Subnet Using Terraform



Requirements

To ensure proper resource provisioning order, the DevOps team wants to explicitly define the dependency between an AWS VPC and a Subnet. The objective is to create a VPC and then a Subnet that explicitly depends on it using Terraform's depends_on argument.

Please complete the following tasks:

  1. Create a VPC named devops-vpc.
  2. Create a Subnet named devops-subnet.
  3. Ensure the Subnet uses the depends_on argument to explicitly depend on the VPC resource.
  4. Create the main.tf file (do not create a separate .tf file) to provision a VPC and Subnet.
  5. Use variables.tf, define the following variables:
    • KKE_VPC_NAME for the VPC name.
    • KKE_SUBNET_NAME for the Subnet name.
  6. Use terraform.tfvars to input the names of the VPC and subnet.
  7. In outputs.tf, output the following:
    • kke_vpc_name: The name of the VPC.
    • kke_subnet_name: The name of the Subnet.

Note

This document focuses on the implementation approach. The task statement above is preserved as the original requirement source.

Prerequisites

  • The Terraform working directory is /home/bob/terraform.
  • Right-click under the EXPLORER section in VS Code and select Open in Integrated Terminal to launch the terminal.

Steps

Create variables.tf:

# /home/bob/terraform/variables.tf
# Variables for VPC and Subnet names

variable "KKE_VPC_NAME" {
description = "The name tag for the AWS VPC."
type = string
}

variable "KKE_SUBNET_NAME" {
description = "The name tag for the AWS Subnet."
type = string
}

Create or update main.tf:

# /home/bob/terraform/main.tf
# AWS VPC and Subnet Resources

# 1. Create the VPC
resource "aws_vpc" "devops_vpc" {
cidr_block = "10.0.0.0/16"
enable_dns_support = true
enable_dns_hostnames = true

tags = {
Name = var.KKE_VPC_NAME
}
}

# 2. Create the Subnet with explicit dependency
resource "aws_subnet" "devops_subnet" {
vpc_id = aws_vpc.devops_vpc.id
cidr_block = "10.0.1.0/24"
map_public_ip_on_launch = true
availability_zone = "us-east-1a"

# Explicitly define dependency on the VPC resource
depends_on = [
aws_vpc.devops_vpc,
]

tags = {
Name = var.KKE_SUBNET_NAME
}
}

Create terraform.tfvars:

# /home/bob/terraform/terraform.tfvars
# Input values for variables

KKE_VPC_NAME = "devops-vpc"
KKE_SUBNET_NAME = "devops-subnet"

Create outputs.tf:

# /home/bob/terraform/outputs.tf
# Output values

output "kke_vpc_name" {
description = "The name of the created VPC."
value = aws_vpc.devops_vpc.tags.Name
}

output "kke_subnet_name" {
description = "The name of the created Subnet."
value = aws_subnet.devops_subnet.tags.Name
}

Run Terraform:

terraform init
# or apply forcefully without creating plan and applying it
terraform apply -auto-approve

Verification

  • Before submitting the task, ensure terraform plan returns No changes. Your infrastructure matches the configuration.
terraform plan

Resources